package cn.iocoder.yudao.module.member.controller.admin.siteagent;

import cn.hutool.core.text.CharSequenceUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.member.controller.admin.siteagent.vo.SiteAgentVo;
import cn.iocoder.yudao.module.member.service.agentsite.SiteAgentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 贴牌管理
 */
@Tag(name = "管理后台 - 贴牌管理")
@RestController
@RequestMapping("/member/site/agent")
@Validated
public class SiteAgentController {

    @Resource
    private FileApi fileApi;

    @Resource
    private SiteAgentService siteAgentService;

    /**
     * member/site/agent/save
     * @param saveReqVO
     * @return
     */
    @PostMapping("/save")
    @Operation(summary = "保存贴牌配置")
    @PreAuthorize("@ss.hasPermission('member:site:agent:save')")
    public CommonResult<Boolean> saveAgentConfig(@Valid @RequestBody SiteAgentVo saveReqVO) {
        siteAgentService.saveConfig(saveReqVO);
        if (CharSequenceUtil.isNotBlank(saveReqVO.getLogoUrl())) {
            fileApi.moveFile(CharSequenceUtil.subAfter(saveReqVO.getLogoUrl(), "/get/", false), "icon");
        }
        return success(true);
    }

    /**
     * member/site/agent/get
     * @return
     */
    @GetMapping("/get")
    @Operation(summary = "获得贴牌配置")
//    @PreAuthorize("@ss.hasPermission('member:site:agent:query')")
    public CommonResult<SiteAgentVo> getAgentConfig() {
        SiteAgentVo config = siteAgentService.getConfig();
        return success(config);
    }

    /**
     * member/site/agent/update
     * @param vo
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "修改贴牌配置")
    @PreAuthorize("@ss.hasPermission('member:site:agent:update')")
    public CommonResult<SiteAgentVo> updateAgentConfig(@RequestBody SiteAgentVo vo) {
        SiteAgentVo config = siteAgentService.updateConfig(vo);
        if (CharSequenceUtil.isNotBlank(vo.getLogoUrl())) {
            fileApi.moveFile(CharSequenceUtil.subAfter(vo.getLogoUrl(), "/get/", false), "icon");
        }
        return success(config);
    }
}
